package soulkun.library.utils.io

import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream

object StreamUtils {

    fun copy(`is`: InputStream, os: OutputStream) {
        copy(`is`, os, ByteArray(1024))
    }

    fun copy(`is`: InputStream, os: OutputStream, buffer: ByteArray?) {
        var len: Int
        try {
            while (`is`.read(buffer).also { len = it } != -1) {
                os.write(buffer, 0, len)
            }
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            RecycleUtils.close(`is`)
            RecycleUtils.close(os)
        }
    }

    fun toString(`is`: InputStream): String? {
        return toString(`is`, ByteArray(1024))
    }

    fun toString(`is`: InputStream, buffer: ByteArray?): String? {
        var len: Int
        val bos = ByteArrayOutputStream()
        try {
            while (`is`.read(buffer).also { len = it } != -1) {
                bos.write(buffer, 0, len)
            }
        } catch (e: IOException) {
            e.printStackTrace()
            return null
        } finally {
            RecycleUtils.close(`is`)
        }
        return bos.toString()
    }

}